//
// Created by 陈宇 on 2017/4/26.
// Copyright (c) 2017 科匠武汉. All rights reserved.
//

import UIKit

func show(_ message: String, delay: TimeInterval = 0, duration: TimeInterval = Delay.short, displayNow: Bool = false) -> Toast? {
    
    guard !message.isEmpty else {return nil}
    
    if displayNow { ToastCenter.default.cancelAll() }

    let toast = Toast(text: message, delay: delay, duration: duration)
    toast.show()
    
    return toast
}

func show(message: String, title: String = "", action: ((UIAlertAction) -> Void)? = nil) {
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    
    if let action = action {
        alert.addAction(UIAlertAction(title: "取消".localized(), style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "确定".localized(), style: .default, handler: action))
    } else {
        alert.addAction(UIAlertAction(title: "确定".localized(), style: .default, handler: nil))
    }

    UIApplication.shared.keyWindow?.endEditing(true)
    UIApplication.shared.rootViewController()?.present(alert, animated: true, completion: nil)
}

extension UIApplication {
    func rootViewController() -> UIViewController? {
        return keyWindow?.rootViewController
    }
}

extension UIViewController {
    
    func show(_ message: String, delay: TimeInterval = 0, duration: TimeInterval = Delay.short, displayNow: Bool = false) -> Toast? {
        
        guard !message.isEmpty else {return nil}
        
        if displayNow { ToastCenter.default.cancelAll() }
        
        let toast = Toast(text: message, delay: delay, duration: duration)
        toast.show()
        
        return toast
    }
    
}
